class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int

        连续非空序列
        """
        count = 0
        prefix_sum = 0
        prefix_sums = {0: 1}  # 初始化前缀和为0的情况

        for num in nums:
            prefix_sum += num
            # prefix_sum[i] - prefix_sum[j] = k  ====>>> nums[j+1] + ... + nums[i] = k
            if prefix_sum - k in prefix_sums:
                count += prefix_sums[prefix_sum - k]
            if prefix_sum in prefix_sums:
                prefix_sums[prefix_sum] += 1
            else:
                prefix_sums[prefix_sum] = 1
            # if not prefix_sum in prefix_sums:
            #     prefix_sums[prefix_sum] = 1


        return count

# 测试示例
nums =  [1, 2, 3, -3, 2, 1]
k = 7

obj = Solution()
print(obj.subarraySum(nums, k))  # 输出应为4，因为有四个子数组和为3: [1, 2], [2, 1], [1, 2], [1, 2, 1]
